<?php
class XMLParser
{
	//IMPORTANT : if $URL is a distant file (http://...), you MUST add "allow_url_include = On" to your php.ini
	private $URL = null;//"../debug.xml"; // http://feeds.feedburner.com/GFGR2?format=xml
	private $DOCUMENT = false;
	private $ARTICLES = array();
	
	function __construct($url=null)
	{
		// Mode normal = feed de l'user
		if(is_null($url))
		{
			// Get Feed URL -- must be defined in the "preferences" table !
			$prefs = Preferences::loadForUser(Session::getFromSession('uid'));
			if(!is_null($prefs->getValue('rss_feed_url')))
				$this->URL = $prefs->getValue('rss_feed_url');
		}
		// Mode cron = tous les feeds de tous les users
		else
		{
			$this->URL = $url;
		}
		
		// LOCAL FILES ONLY -- MAKE SURE TO COMMENT THIS LINE IF USING A DISTANT URL !!
		//$this->URL = realpath($this->URL);
		
		$doc = new DOMDocument();
		$doc->load($this->URL);
		$this->DOCUMENT = $doc;
		
		$items = $doc->getElementsByTagName("item");
		$articles = array();
				
		foreach ($items as $item)
		{
		 	$article = array();
			if($item->childNodes->length) 
			{
				foreach($item->childNodes as $i)
				{
					$article[$i->nodeName] = utf8_decode( $i->nodeValue ); // will be reencoded in utf8 later
				}
			}
			$articles[] = $article;
		}
		
		$this->ARTICLES = $articles;	
	}
	
	function getFeedURL()
	{
		return $this->URL;
	}
	
	function getArticles()
	{
		return $this->ARTICLES;
	}
	
	function getArticleById($id)
	{
		return $this->ARTICLES[$id];
	}
	
	function getArticleProperty($id, $property)
	{
		return $this->ARTICLES[$id][$property];
	}
	
	function storeArticlesAsNotes()
	{
		$res = array();
		foreach($this->getArticles() as $article)
		{
			$link = "<p><a href=\"".$article['link']."\">".$article['link']."</a></p>";
			
			$note = new Note();
			$note->setTitle($article['title']);
			$note->setAuthor($article['dc:creator']);
			$note->setBody($link . $article['description']);
			$note->setCategoryId(1);
			$done = $note->create(); // return false if item already exists
			
			if($done)
				$res[] = $article['title'];
		}
		return $res;
	}
	
	function storeArticles()
	{
		$res = array();
		foreach($this->getArticles() as $article)
		{
			$a = new Articles();
			$a->setTitle($article['title']);
			$a->setLink($article['link']);
			$a->setAuthor($article['dc:creator']);
			$a->setDatePublished(formatDate("Y-m-d H:i:s", $article['pubDate']));
			//$a->setDateCreated($data['date_created']);
			//$a->setDateUpdated($data['date_updated']);
			$a->setBody($article['description']);
			//$a->setComment($data['comment']);
			//$a->setCategoryId($data['category_id']);
			//$a->setHash($data['hash']);
			//$a->setCited($data['cited']);
			//$a->setDateCited($data['date_cited']);
			$done = $a->create();
			
			if($done)
				$res[] = $article['title'];
		}
		return $res;
	}

	
}
?>